//
//  DSXRosterViewController.m
//  DerbyOSSampler
//
//  Created by glenn andreas on 3/21/14.
//  Copyright (c) 2014 glenn andreas. All rights reserved.
//

#import "DSXRosterViewController.h"
#import "DXMLTeamObject.h"
#import "DXMLPersonObject.h"
#import "DerbyNSOde.h"
#import "DXMLBoutObject.h"
@implementation DSXRosterViewController
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.team.skatersInRosterOrder count];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Skater" forIndexPath:indexPath];
    UILabel *number = (UILabel *)[cell viewWithTag:1];
    UILabel *name = (UILabel *)[cell viewWithTag:2];
    DXMLPersonObject *person = [self.team.skatersInRosterOrder objectAtIndex:indexPath.row];
    name.text = person.name;
    number.text = person.number;
    return cell;
}
- (IBAction)addSkater:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add Skater" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil];
    alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    [[alert textFieldAtIndex:0] setPlaceholder:@"Skater Name"];
    [[alert textFieldAtIndex:1] setPlaceholder:@"Skater Number"];
    [[alert textFieldAtIndex:1] setSecureTextEntry:NO];
    
    [alert show];
}
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == [alertView firstOtherButtonIndex]) {
        NSString *name = [alertView textFieldAtIndex:0].text;
        NSString *number = [alertView textFieldAtIndex:1].text;
        if (number.length) {
            DXMLPersonObject *person = [self.team skaterForNumber:number create:YES];
            person.name = name;
            [self.tableView reloadData];
            // for now manually call the NSOde message sending.t
            DXMLObject *msg = [[DXMLObject alloc] initWithElementName:@"add" attributes:@{@"team":[NSString stringWithFormat:@"%d",[self.nsode.xml.teams indexOfObject: self.team]]}];
            DXMLObject *body = [[DXMLObject alloc] initWithElementName:@"person" attributes:@{
                                                                                              @"name":name,
                                                                                              @"number":number
                                                                                              }];
            [msg addChild:body];
            [self.nsode sendXML:msg];
        }
    }
}
@end
